const HOST_NAME = location.host;
const VERSION_NAME = 'CACHE-v2';
const CACHE_NAME = HOST_NAME + '-' + VERSION_NAME;
const CACHE_HOST = ['cdn.bootcss.com'];

const sentMessage = function(msg) {
    self.clients.matchAll().then(function(clients) {
        clients.forEach(function(client) {
            client.postMessage(msg);
        })
    });
};

const isNeedCache = function(url) {
    return CACHE_HOST.some(function(host) {
        return url.search(host) !== -1;
    });
};

const isCORSRequest = function(url, host) {
    return url.search(host) === -1;
};

const isValidResponse = function(response) {
    return response && response.status >= 200 && response.status < 400;
};

self.addEventListener('message', function(event) {
    console.log(event.data);
    event.ports[0].postMessage('[service worker] thanks i will work better version 16.');
});

const handleFetchRequest = function(req) {
    if (isNeedCache(req.url)) {
        const request = isCORSRequest(req.url, HOST_NAME) ? new Request(req.url, {mode: 'cors'}) : req;
        return caches.match(request)
            .then(function(response) {
                // Cache hit - return response directly
                if (response) {
                    // Update Cache for next time enter
                    if(isValidResponse(response)) {
                        fetch(request)
                            .then(function (response) {

                                // Check a valid response
                                if (isValidResponse(response)) {
                                    caches
                                        .open(CACHE_NAME)
                                        .then(function (cache) {
                                            cache.put(request, response);
                                        });
                                } else {
                                    sentMessage('Update cache ' + request.url + ' fail: ' + response.message);
                                }
                            })
                            .catch(function (err) {
                                sentMessage('Update cache ' + request.url + ' fail: ' + err.message);
                            });
                    }
                    return response;
                }

                console.log('-------------------');
                console.log("你怎么冲过来了");
                console.log('-------------------');

                // Return fetch response
                return fetch(request)
                    .then(function(response) {
                        // Check if we received an unvalid response
                        if(!isValidResponse(response)) {
                            return response;
                        }

                        const clonedResponse = response.clone();

                        caches
                            .open(CACHE_NAME)
                            .then(function(cache) {
                                cache.put(request, clonedResponse);
                            });

                        return response;
                    });
            });
    }
    else {
        return fetch(req);
    }
};

const onFetch = function(event) {
    if (isNeedCache(event.request.url)) {
        event.respondWith(handleFetchRequest(event.request));
    }
};

self.addEventListener('fetch', onFetch);

const onActive = function(event) {
    event.waitUntil(
        Promise.all(
            [
                self.clients.claim(),
                new Promise(function (resolve, reject) {
                    caches
                        .keys()
                        .then(function(cacheNames) {
                            return Promise.all(
                                cacheNames.map(function(cacheName) {
                                    // Remove expired cache response
                                    if (CACHE_NAME.indexOf(cacheName) === -1) {
                                        return caches.delete(cacheName);
                                    }
                                })
                            ).then(function () {
                                resolve();
                            }).catch(function (e) {
                                reject(e);
                            })
                        })
                })
            ]
        )
        // caches
        //     .keys()
        //     .then(function(cacheNames) {
        //         return Promise.all(
        //             cacheNames.map(function(cacheName) {
        //                 // Remove expired cache response
        //                 if (CACHE_NAME.indexOf(cacheName) === -1) {
        //                     return caches.delete(cacheName);
        //                 }
        //             })
        //         );
        //     })
        //     .then(function() {
        //         console.log('[service worker] Active success');
        //         self.clients.claim();
        //     })
    );
};

self.addEventListener('activate', onActive);

self.addEventListener('install', function(event) {
    event.waitUntil(
        Promise.all(
            [
                self.skipWaiting(),
                new Promise(function (resolve, reject) {
                    caches
                        .open(CACHE_NAME)
                        .then(function () {
                            resolve();
                        }).catch(function (e) {
                            reject(e);
                        })
                })
            ]
        )
        // caches
        //     .open(CACHE_NAME)
        //     .then(function() { console.log('[service worker] Install success'); self.skipWaiting(); })
    );
});